<template>
  <div>
    <!-- 页头 -->
    <NavBar />
    <div class="reservation-container">
      <h2>预约服务</h2>
      <!-- 选择服务大类 -->
      <div class="category-section">
        <h3>选择服务类型</h3>
        <div class="category-list">
          <button
            v-for="cat in categories"
            :key="cat.key"
            :class="['category-btn', { active: selectedCategory === cat.key }]"
            @click="selectCategory(cat.key)"
          >
            {{ cat.name }}
          </button>
        </div>
      </div>
      <!-- 选择服务项目（多选） -->
      <div v-if="selectedCategory" class="service-section">
        <h3>选择服务项目</h3>
        <div class="service-list">
          <div
            v-for="srv in currentServices"
            :key="srv.key"
            :class="['service-card', { selected: selectedService.includes(srv.key) }]"
            @click="toggleService(srv)"
          >
            <div class="service-title">{{ srv.name }}</div>
            <div class="service-desc">{{ srv.desc }}</div>
            <div class="service-price">￥{{ srv.price }}</div>
          </div>
        </div>
      </div>
      <!-- 选择日期（完整日历） -->
      <div v-if="selectedService.length" class="datetime-section">
        <h3>选择日期</h3>
        <div class="calendar">
          <div class="calendar-header">
            <button class="calendar-arrow" @click="prevMonth">&lt;</button>
            <span>{{ calendarYear }} 年 {{ calendarMonth + 1 }} 月</span>
            <button class="calendar-arrow" @click="nextMonth">&gt;</button>
          </div>
          <div class="calendar-body">
            <div class="calendar-row calendar-weekdays">
              <span v-for="d in weekDays" :key="d">{{ d }}</span>
            </div>
            <div v-for="(row, rowIdx) in calendarRows" :key="rowIdx" class="calendar-row">
              <span
                v-for="cell in row"
                :key="cell.dateStr"
                :class="['calendar-cell',
                  { today: cell.isToday, selected: cell.isSelected, disabled: cell.isDisabled }]
                "
                @click="selectDate(cell)"
              >
                {{ cell.day || '' }}
              </span>
            </div>
          </div>
        </div>
        <h3>选择时间</h3>
        <div class="time-select">
          <button 
            v-for="t in timeOptions" 
            :key="t" 
            :class="['time-btn', { 
              active: selectedTime === t, 
              disabled: isTimeDisabled(t) 
            }]"
            @click="!isTimeDisabled(t) && (selectedTime = t)"
          >
            {{ t }}
          </button>
        </div>
      </div>
      <!-- 备注 -->
      <div v-if="selectedService.length" class="remark-section">
        <h3>备注</h3>
        <textarea v-model="remark" placeholder="请输入备注（可选）"></textarea>
      </div>
      <!-- 总价和预约按钮 -->
      <div v-if="selectedService.length" class="summary-section">
        <div class="total-price">总计：<span>￥{{ selectedPrice }}</span></div>
        <button class="btn" @click="submitReservation">立即预约</button>
      </div>
    </div>
    <!-- 页脚 -->
    <PageFooter />
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import NavBar from '@/components/NavBar.vue';
import PageFooter from '@/components/PageFooter.vue';

// 服务大类
const categories = [
  { key: 'grooming', name: '宠物美容' },
  { key: 'medical', name: '宠物医疗' },
  { key: 'training', name: '宠物训练' },
  { key: 'boarding', name: '宠物寄养' },
];

// 各大类下的服务项目（通用结构，后续可扩展）
const servicesMap = {
  grooming: [
    { key: 'grooming1', name: '洗护护理', desc: '专业洗护护理服务', price: 188 },
    { key: 'grooming2', name: '美容造型', desc: '宠物美容造型设计', price: 268 },
    { key: 'grooming3', name: '健康体检', desc: '宠物健康体检套餐', price: 388 },
    { key: 'grooming4', name: '深度护理', desc: '深层皮毛护理', price: 288 },
  ],
  medical: [
    { key: 'medical1', name: '常规体检', desc: '基础健康检查', price: 200 },
    { key: 'medical2', name: '疫苗接种', desc: '宠物疫苗服务', price: 150 },
    { key: 'medical3', name: '疾病诊疗', desc: '常见疾病诊疗', price: 300 },
    { key: 'medical4', name: '手术治疗', desc: '宠物手术服务', price: 800 },
  ],
  training: [
    { key: 'training1', name: '基础服从', desc: '基础行为训练', price: 180 },
    { key: 'training2', name: '技能训练', desc: '专项技能训练', price: 260 },
    { key: 'training3', name: '行为矫正', desc: '不良行为矫正', price: 320 },
    { key: 'training4', name: '社交训练', desc: '社交能力提升', price: 220 },
  ],
  boarding: [
    { key: 'boarding1', name: '标准寄养', desc: '基础寄养服务', price: 100 },
    { key: 'boarding2', name: '豪华寄养', desc: '高端寄养环境', price: 200 },
    { key: 'boarding3', name: '医疗寄养', desc: '带医疗护理寄养', price: 300 },
    { key: 'boarding4', name: '特殊寄养', desc: '特殊需求寄养', price: 400 },
  ],
};

const selectedCategory = ref('');
const selectedService = ref([]); // 多选
const selectedTime = ref('09:00');
const remark = ref('');

// 日历相关
const today = new Date();
const calendarYear = ref(today.getFullYear());
const calendarMonth = ref(today.getMonth()); // 0-11
const selectedDate = ref(formatDate(today));

function formatDate(date) {
  const y = date.getFullYear();
  const m = String(date.getMonth() + 1).padStart(2, '0');
  const d = String(date.getDate()).padStart(2, '0');
  return `${y}-${m}-${d}`;
}

const weekDays = ['日', '一', '二', '三', '四', '五', '六'];

const calendarRows = computed(() => {
  const year = calendarYear.value;
  const month = calendarMonth.value;
  const firstDay = new Date(year, month, 1);
  const lastDay = new Date(year, month + 1, 0);
  const daysInMonth = lastDay.getDate();
  const rows = [];
  let row = [];
  let dayOfWeek = firstDay.getDay();
  // 填充月初空白
  for (let i = 0; i < dayOfWeek; i++) {
    row.push({ day: '', dateStr: '', isToday: false, isSelected: false, isDisabled: true });
  }
  for (let d = 1; d <= daysInMonth; d++) {
    const dateObj = new Date(year, month, d);
    const dateStr = formatDate(dateObj);
    const isToday = dateStr === formatDate(today);
    const isSelected = dateStr === selectedDate.value;
    const isDisabled = dateObj < new Date(today.getFullYear(), today.getMonth(), today.getDate());
    row.push({
      day: d,
      dateStr,
      isToday,
      isSelected,
      isDisabled
    });
    if (row.length === 7) {
      rows.push(row);
      row = [];
    }
  }
  // 填充月末空白
  if (row.length) {
    while (row.length < 7) {
      row.push({ day: '', dateStr: '', isToday: false, isSelected: false, isDisabled: true });
    }
    rows.push(row);
  }
  return rows;
});

function prevMonth() {
  if (calendarMonth.value === 0) {
    calendarYear.value--;
    calendarMonth.value = 11;
  } else {
    calendarMonth.value--;
  }
}
function nextMonth() {
  if (calendarMonth.value === 11) {
    calendarYear.value++;
    calendarMonth.value = 0;
  } else {
    calendarMonth.value++;
  }
}
function selectDate(cell) {
  if (!cell.isDisabled && cell.day) {
    selectedDate.value = cell.dateStr;
  }
}

const timeOptions = [
  '09:00', '10:00', '11:00', '14:00', '15:00', '16:00', '17:00'
];

const currentServices = computed(() => {
  return selectedCategory.value ? servicesMap[selectedCategory.value] : [];
});

const selectedPrice = computed(() => {
  if (!selectedCategory.value || !selectedService.value.length) return 0;
  return selectedService.value
    .map(key => servicesMap[selectedCategory.value].find(s => s.key === key)?.price || 0)
    .reduce((a, b) => a + b, 0);
});

function selectCategory(key) {
  selectedCategory.value = key;
  selectedService.value = [];
}
function toggleService(srv) {
  const idx = selectedService.value.indexOf(srv.key);
  if (idx > -1) {
    selectedService.value.splice(idx, 1);
  } else {
    selectedService.value.push(srv.key);
  }
}

// 添加判断时间是否禁用的方法
function isTimeDisabled(time) {
  // 如果不是今天，则不禁用
  if (selectedDate.value !== formatDate(today)) return false;
  
  // 如果是今天，判断时间是否已过
  const [hours, minutes] = time.split(':').map(Number);
  const now = new Date();
  
  if (hours < now.getHours()) return true;
  if (hours === now.getHours() && minutes <= now.getMinutes()) return true;
  
  return false;
}

function submitReservation() {
  if (isTimeDisabled(selectedTime.value)) {
    alert('请选择有效的预约时间！');
    return;
  }
  
  // 这里只做简单演示，实际可接入后端
  const serviceNames = selectedService.value.map(key => currentServices.value.find(s => s.key === key)?.name).join('、');
  alert(`预约成功！\n服务类型：${categories.find(c=>c.key===selectedCategory.value)?.name}\n服务项目：${serviceNames}\n日期：${selectedDate.value}\n时间：${selectedTime.value}\n备注：${remark.value}\n总价：￥${selectedPrice.value}`);
}
</script>

<script>
export default {
  name: 'ServiceReservation'
}
</script>

<style scoped>
.reservation-container {
  max-width: 900px;
  margin: 40px auto;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 8px 24px rgba(0,0,0,0.08);
  padding: 40px 32px 32px 32px;
}
h2 {
  text-align: center;
  margin-bottom: 32px;
}
.category-section, .service-section, .datetime-section, .remark-section, .summary-section {
  margin-bottom: 32px;
}
.category-list {
  display: flex;
  gap: 24px;
  justify-content: center;
  margin-top: 16px;
}
.category-btn {
  background: #f4f4f4;
  border: none;
  border-radius: 8px;
  padding: 16px 32px;
  font-size: 18px;
  cursor: pointer;
  transition: background 0.2s, color 0.2s;
}
.category-btn.active, .category-btn:hover {
  background: #e76f51;
  color: #fff;
}
.service-list {
  display: flex;
  gap: 24px;
  flex-wrap: wrap;
  justify-content: center;
  margin-top: 16px;
}
.service-card {
  width: 200px;
  background: #f9f9f9;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
  padding: 20px 16px;
  cursor: pointer;
  border: 2px solid transparent;
  transition: border 0.2s, box-shadow 0.2s;
}
.service-card.selected, .service-card:hover {
  border: 2px solid #e76f51;
  box-shadow: 0 4px 16px rgba(231,111,81,0.08);
}
.service-title {
  font-weight: bold;
  font-size: 18px;
  margin-bottom: 8px;
}
.service-desc {
  font-size: 14px;
  color: #888;
  margin-bottom: 12px;
}
.service-price {
  color: #e76f51;
  font-weight: bold;
  font-size: 16px;
}
/* 日历样式 */
.calendar {
  margin: 16px 0 24px 0;
  background: #fafbfc;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.03);
  padding: 24px 24px 12px 24px;
}
.calendar-header {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 12px;
  gap: 24px;
}
.calendar-arrow {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #e76f51;
  padding: 0 8px;
  border-radius: 4px;
  transition: background 0.2s;
}
.calendar-arrow:hover {
  background: #fbe8dc;
}
.calendar-body {
  width: 100%;
}
.calendar-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 4px;
}
.calendar-weekdays {
  color: #aaa;
  font-size: 15px;
  font-weight: 500;
  margin-bottom: 8px;
}
.calendar-cell {
  width: 38px;
  height: 38px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  margin: 1px;
  transition: background 0.2s, color 0.2s;
}
.calendar-cell.today {
  border: 1.5px solid #e76f51;
}
.calendar-cell.selected {
  background: #e76f51;
  color: #fff;
}
.calendar-cell.disabled {
  color: #ccc;
  background: #f4f4f4;
  cursor: not-allowed;
}
.datetime-section select {
  margin-top: 8px;
  padding: 8px 12px;
  border-radius: 6px;
  border: 1px solid #ccc;
  font-size: 16px;
  margin-right: 16px;
}
.remark-section textarea {
  width: 100%;
  min-height: 60px;
  border-radius: 8px;
  border: 1px solid #ccc;
  padding: 10px;
  font-size: 16px;
  margin-top: 8px;
  resize: vertical;
}
.summary-section {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 24px;
}
.total-price {
  font-size: 20px;
  color: #e76f51;
  font-weight: bold;
}
.btn {
  background-color: #e76f51;
  color: white;
  padding: 14px 36px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 600;
  font-size: 18px;
  transition: background-color 0.3s;
}
.btn:hover {
  background-color: #d65c41;
}

/* 时间选择按钮组 */
.time-select {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-top: 16px;
  width: 100%;
}
.time-btn {
  flex: 1;
  min-width: 80px;
  padding: 12px 6px;
  border: 1px solid #ddd;
  border-radius: 8px;
  background: white;
  cursor: pointer;
  transition: all 0.2s;
  font-size: 16px;
}
.time-btn:hover:not(.disabled) {
  border-color: #e76f51;
}
.time-btn.active {
  background: #e76f51;
  color: white;
  border-color: #e76f51;
}
.time-btn.disabled {
  background: #f4f4f4;
  color: #bbb;
  cursor: not-allowed;
}
</style> 